package com.mpgame.common.network;

import java.util.concurrent.TimeUnit;

import com.mpgame.common.manager.HeartbeatMgr;
import com.mpgame.common.proto.GamePacket;
import com.mpgame.common.utils.Log;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

public class NetTcpClient {
    private final String host;
    private final int port;
    private final HeartbeatMgr heartbeatMgr = new HeartbeatMgr();

    public NetTcpClient(String host, int port){
        this.host = host;
        this.port = port;
    }

    /**
     * 连接到服务器
     */
    public void connect(ChannelInboundHandlerAdapter businessHandler) throws InterruptedException{
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .handler(new ChannelInitializer<Channel>(){
                @Override
                protected void initChannel(Channel ch){
                    ch.pipeline()
                     .addLast(new ProtobufVarint32FrameDecoder())
                     .addLast(new ProtobufDecoder(GamePacket.getDefaultInstance()))
                     .addLast(new ProtobufVarint32LengthFieldPrepender())
                     .addLast(new ProtobufEncoder())
                     .addLast(new IdleStateHandler(90, 0, 0, TimeUnit.SECONDS))
                     .addLast(new ChannelDuplexHandler(){
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception{
                            if(evt instanceof IdleStateEvent){
                                IdleStateEvent event = (IdleStateEvent)evt;
                                if(event.state() == IdleState.READER_IDLE){
                                    Log.err("长时间未收到数据，关闭连接");
                                    ctx.close();
                                }
                            }
                        }
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
                            Log.err("连接异常：" + cause.getMessage());
                            ctx.close();
                        }
                     })
                    .addLast(businessHandler);
                }
             });

            ChannelFuture f = b.connect(host, port).sync();
            heartbeatMgr.startHeartbeat(f.channel());
            Log.info("客户端连接到" + host + ":" + port);
            f.channel().closeFuture().sync();
        }
        finally{
            group.shutdownGracefully();
        }
    }
}
